<?php if (!defined('NOVA_RUN')) die('You can\'t access this file directly!');

/*
-------------------------------------------------------
*
*   NovaBoard 2
*   Copyright © 2011 NovaBoard team
*
*--------------------------------------------------------
*
*   Official site: www.novaboard.net
*   Contact e-mail: support@novaboard.net
*
*   GNU General Public License, version 2:
*   http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
---------------------------------------------------------
*/

class User_Object extends Object {

	var $info = array();
	var $permissions;
	var $logout_hash;

	public function __construct($id)
	{
		parent::__construct();

		if ($id > 0)
		{
			$stmt = db::instance()->select('userGetInfo', array
			(
				'fields'	=> '*',
				'tables'	=> 'users',
				'short'		=> array('users' => 'u'),
				'where'		=> array('u.user_id' => array('=', '?')),
				'limit'		=> 1,
				'joins'		=> array(
					array(
						'type'		=> 'inner',
						'table'		=> 'sessions',
						'short'		=> 's',
						'conditions'=>array('s.user_id' => 'u.user_id')
			))));
			$stmt->execute(array($id));
			$this->info = $stmt->fetch();

			$this->logout_hash = $this->info['logout_hash'];
		}
		else
		{
			$this->info['user_id'] = 0;
			$this->info['group_id'] = 0;
			$this->logout_hash = "";
		}

		// try to get permissions from cache
		if (!$this->permissions = Cache::load('group_permissions_'.$this->info['group_id']))
		{
			// get from db
			$stmt = db::instance()->select('userGetGroupPermissions', array
			(
				'fields'	=> '*',
				'tables'	=> 'group_permissions',
				'where'		=> array('group_id' => array('=', '?')),
				'limit'		=> 1
			));

			$stmt->execute(array($this->info['group_id']));
			$this->permissions = $stmt->fetch();

			// save cache
			Cache::save('group_permissions_'.$this->info['group_id'], $this->permissions);
		}
	}

	public function reGetPermissions()
	{
		// try to get permissions from cache
		if (!$this->permissions = Cache::load('group_permissions_'.$this->info['group_id']))
		{
			// get from db
			$stmt = db::instance()->select('userGetGroupPermissions', array
			(
				'fields'	=> '*',
				'tables'	=> 'group_permissions',
				'where'		=> array('group_id' => array('=', '?')),
				'limit'		=> 1
			));

			$stmt->execute(array($this->info['group_id']));
			$this->permissions = $stmt->fetch();

			// save cache
			Cache::save('group_permissions_'.$this->info['group_id'], $this->permissions);
		}
	}
}
